package pl.diagnoser.server.persistance.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import pl.diagnoser.client.dto.UserDTO;
import pl.diagnoser.server.persistance.map.App;
import pl.diagnoser.server.persistance.map.User;
import pl.diagnoser.server.persistance.tools.HibernateUtil;

public class UserDao implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	public List<UserDTO> getUserList() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		List<User> users = new ArrayList<User>(session.createQuery("from User").list());
		List<UserDTO> usersDTO = 
				new ArrayList<UserDTO>(users != null ? users.size() : 0);
		
		if(users != null) {
			for(User user : users) {
				usersDTO.add(createUserDTO(user));
			}
		}
		
		return usersDTO;
	}
	
	public UserDTO getUser(String login, String password) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		User user = (User)session.createCriteria(User.class).add(Restrictions.eq("login", login)).add(Restrictions.eq("password", password)).uniqueResult();
		
		session.getTransaction().commit();
		session.close();
		if(user != null) {
			UserDTO userDTO = createUserDTO(user);
			App app = new AppDao().getActiveApp();
			if(app != null) {
				userDTO.setAppId(app.getAppId());
				userDTO.setIsSearchMode(app.getIsSearchMode());
			}
			return userDTO;
		}
		else
			return null;
	}
	
	public String saveUser(UserDTO user) {
		String ret = "OK";
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		try {
	    	session.save(new User(user));
	    	session.getTransaction().commit();
	    } catch(Exception e) {
	    	ret = e.getMessage();
	    } finally {
			session.close();
	    }
		
		return ret;
	}
	
	public String removeUser(long userID) {
		String ret = "OK";
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		try {
			User tmpUser = (User) session.createCriteria(User.class).add(Expression.eq("userID", userID)).uniqueResult();
			session.delete(tmpUser);
	    	session.getTransaction().commit();
	    } catch(Exception e) {
	    	ret = e.getMessage();
	    } finally {
			session.close();
	    }
		
		return ret;
	}
	
	private UserDTO createUserDTO(User user) {
		return new UserDTO(user.getUserID(),
				user.getName(),
				user.getLastname(),
				user.getLogin(),
				user.getPassword(),
				user.getIsAdministrator());
	}
}
